package com.superb.system.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.superb.common.core.annotation.SuperbDataScope;
import com.superb.common.core.annotation.SuperbRestMapping;
import com.superb.common.core.enums.DeviceType;
import com.superb.common.core.model.Result;
import com.superb.system.api.dto.UserOnLine;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ajie
 * @CreateTime: 2024-07-23 11:17
 */
@SuperbDataScope
@Tag(name = "用户在线情况")
@SuperbRestMapping("userOnline")
@ApiSupport(author = "ajie: ajie20999@163.com", order = 9)
public class UserOnLineController {

    @GetMapping("list/{userId}")
    @Operation(summary = "获取用户登录列表", parameters = {
            @Parameter(name = "userId", description = "用户id", required = true)
    })
    public Result<List<UserOnLine>> onlineList(@PathVariable String userId) {
        List<UserOnLine> list = new ArrayList<>();
        // 1. 根据用户id获取会话
        SaSession session = StpUtil.getSessionByLoginId(userId);
        // 2. 根据会话列表获取登录信息
        List<TokenSign> signs = session.getTokenSignList();
        for (TokenSign sign : signs) {
            JSONObject tag = (JSONObject)sign.getTag();
            UserOnLine userOnLine = tag.toJavaObject(UserOnLine.class);
            userOnLine.setDeviceType(DeviceType.of(sign.getDevice()));
            userOnLine.setToken(sign.getValue());
            list.add(userOnLine);
        }
        return Result.success(list);
    }

    @GetMapping("logout/{token}")
    @Operation(summary = "注销登录用户", parameters = {
            @Parameter(name = "token", description = "用户登录凭证", required = true)
    })
    public Result<List<UserOnLine>> logout(@PathVariable String token) {
        StpUtil.logoutByTokenValue(token);
        return Result.success();
    }

    @GetMapping("kickout/{token}")
    @Operation(summary = "踢下线", parameters = {
            @Parameter(name = "token", description = "用户登录凭证", required = true)
    })
    public Result<List<UserOnLine>> kickout(@PathVariable String token) {
        StpUtil.kickoutByTokenValue(token);
        return Result.success();
    }

}
